package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {
    @Resource
    private AgencyCertificationMapper agencyCertificationMapper;
    @Resource
    private AgencyCertificationAuditMapper agencyCertificationAuditMapper;

    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId())
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    /**
     * 提交认证相关接口
     *
     * @param agencyCertificationAuditAddReqDTO
     */
    @Override
    @Transactional
    public void agencyCertificationAudit(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        AgencyCertification agencyCertification = BeanUtil.toBean(agencyCertificationAuditAddReqDTO, AgencyCertification.class);
        agencyCertification.setBusinessLicense(agencyCertificationAuditAddReqDTO.getBusinessLicense());
        agencyCertification.setLegalPersonIdCardNo(agencyCertificationAuditAddReqDTO.getLegalPersonIdCardNo());
        CurrentUserInfo currentUser = UserContext.getCurrentUser();
        if (currentUser != null) {
            // 使用getId()方法获取Long类型的用户ID
            agencyCertification.setId(currentUser.getId());
        } else {
            throw new IllegalStateException("无法获取当前用户信息");
        }
        agencyCertification.setIdNumber(agencyCertificationAuditAddReqDTO.getIdNumber());
        agencyCertification.setLegalPersonName(agencyCertificationAuditAddReqDTO.getLegalPersonName());
        agencyCertification.setName(agencyCertificationAuditAddReqDTO.getName());
        agencyCertification.setCertificationStatus(1);
        //添加到数据库
        agencyCertificationMapper.insert(agencyCertification);
        AgencyCertificationAudit agencyCertificationAudit = BeanUtil.toBean(agencyCertificationAuditAddReqDTO, AgencyCertificationAudit.class);
        agencyCertificationAudit.setBusinessLicense(agencyCertificationAuditAddReqDTO.getBusinessLicense());
        agencyCertificationAudit.setLegalPersonIdCardNo(agencyCertificationAuditAddReqDTO.getLegalPersonIdCardNo());
        agencyCertificationAudit.setServeProviderId(currentUser.getId());
        agencyCertificationAudit.setIdNumber(agencyCertificationAuditAddReqDTO.getIdNumber());
        agencyCertificationAudit.setLegalPersonName(agencyCertificationAuditAddReqDTO.getLegalPersonName());
        agencyCertificationAudit.setName(agencyCertificationAuditAddReqDTO.getName());
        agencyCertificationAudit.setCertificationStatus(1);
        agencyCertificationAudit.setAuditStatus(0);
        //添加到数据库
        agencyCertificationAuditMapper.insert(agencyCertificationAudit);

    }

    /**
     * 机构分页查询
     *
     * @param agencyCertificationAuditPageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> pageQuery(AgencyCertificationAuditPageQueryReqDTO agencyCertificationAuditPageQueryReqDTO) {
        //1.分页查询用户
        Page<AgencyCertificationAudit> page = PageUtils.parsePageQuery(agencyCertificationAuditPageQueryReqDTO, AgencyCertificationAudit.class);
        LambdaQueryWrapper<AgencyCertificationAudit> queryWrapper = Wrappers.<AgencyCertificationAudit>lambdaQuery()
                .like(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getName()), AgencyCertificationAudit::getName, agencyCertificationAuditPageQueryReqDTO.getName())
                .eq(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getLegalPersonName()), AgencyCertificationAudit::getLegalPersonName, agencyCertificationAuditPageQueryReqDTO.getLegalPersonName())
                .eq(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getCertificationStatus()), AgencyCertificationAudit::getCertificationStatus, agencyCertificationAuditPageQueryReqDTO.getCertificationStatus())
                .eq(ObjectUtil.isNotEmpty(agencyCertificationAuditPageQueryReqDTO.getAuditStatus()), AgencyCertificationAudit::getAuditStatus, agencyCertificationAuditPageQueryReqDTO.getAuditStatus());
        Page<AgencyCertificationAudit> agencyCertificationAuditPage = agencyCertificationAuditMapper.selectPage(page, queryWrapper);
        //2.封装数据
        return PageUtils.toPage(agencyCertificationAuditPage, AgencyCertificationAuditResDTO.class);
    }

    /**
     * 审核
     *
     * @param certificationAuditReqDTO
     * @param id
     */
    @Override
    @Transactional
    public void auditById(CertificationAuditReqDTO certificationAuditReqDTO, Long id) {
        //根据申请id获取申请信息
        AgencyCertificationAudit agencyCertificationAudit = agencyCertificationAuditMapper.selectById(id);
        if (certificationAuditReqDTO.getCertificationStatus() == 2) {
            //成功的话修改数据库
            agencyCertificationAudit.setAuditStatus(1);
            agencyCertificationAudit.setAuditTime(LocalDateTime.now());
            agencyCertificationAudit.setUpdateTime(LocalDateTime.now());
            agencyCertificationAudit.setCertificationStatus(2);
            CurrentUserInfo currentUser = UserContext.getCurrentUser();
            if (currentUser != null) {
                // 使用getId()方法获取Long类型的用户ID
                agencyCertificationAudit.setAuditorId(currentUser.getId());
                agencyCertificationAudit.setAuditorName(currentUser.getName());
            } else {
                throw new IllegalStateException("无法获取当前用户信息");
            }
            agencyCertificationAuditMapper.updateById(agencyCertificationAudit);
            AgencyCertification agencyCertification = agencyCertificationMapper.selectById(agencyCertificationAudit.getServeProviderId());
            agencyCertification.setCertificationStatus(2);
            agencyCertification.setCertificationTime(LocalDateTime.now());
            agencyCertification.setUpdateTime(LocalDateTime.now());
            agencyCertificationMapper.updateById(agencyCertification);
        } else {
            //失败就该状态
            agencyCertificationAudit.setAuditStatus(1);
            agencyCertificationAudit.setAuditTime(LocalDateTime.now());
            agencyCertificationAudit.setUpdateTime(LocalDateTime.now());
            agencyCertificationAudit.setCertificationStatus(3);
            agencyCertificationAudit.setRejectReason(certificationAuditReqDTO.getRejectReason());
            CurrentUserInfo currentUser = UserContext.getCurrentUser();
            if (currentUser != null) {
                // 使用getId()方法获取Long类型的用户ID
                agencyCertificationAudit.setAuditorId(currentUser.getId());
                agencyCertificationAudit.setAuditorName(currentUser.getName());
            } else {
                throw new IllegalStateException("无法获取当前用户信息");
            }
            agencyCertificationAuditMapper.updateById(agencyCertificationAudit);
            AgencyCertification agencyCertification = agencyCertificationMapper.selectById(agencyCertificationAudit.getServeProviderId());
            agencyCertification.setCertificationStatus(3);
            agencyCertification.setCertificationTime(LocalDateTime.now());
            agencyCertification.setUpdateTime(LocalDateTime.now());
            agencyCertificationMapper.updateById(agencyCertification);
        }
    }

    /**
     * 查询最新的驳回原因接口
     *
     * @return
     */
    @Override
    public RejectReasonResDTO rejectReason() {
        //匹配审核表中机构ID等于当前用户id的数据中最新的驳回原因
        AgencyCertificationAudit agencyCertificationAudit = agencyCertificationAuditMapper.selectOne(
                Wrappers.<AgencyCertificationAudit>lambdaQuery()
                        .eq(AgencyCertificationAudit::getServeProviderId, UserContext.currentUserId())
                        .orderByDesc(AgencyCertificationAudit::getAuditTime)
                        .last("limit 1")
                        .select(AgencyCertificationAudit::getRejectReason)
        );
        RejectReasonResDTO rejectReasonResDTO = new RejectReasonResDTO();
        if (agencyCertificationAudit != null) {
            rejectReasonResDTO.setRejectReason(agencyCertificationAudit.getRejectReason());
        }
        return rejectReasonResDTO;
    }
}
